﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LoongEgg.Core;

namespace BinViewer
{
    public class BinReader : BindableObject
    {
        public static Char HexSpliter { get; set; } = ' ';
        public double Progress => (BinaryReader == null ? 0 : 100.0 * BinaryReader.BaseStream.Position / BinaryReader.BaseStream.Length);
        public FileStream FileStream { get; private set; }
        public BinaryReader BinaryReader { get; private set; }
        public bool IsFileOpen { get; private set; }

        public void Open(string path)
        {
            FileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryReader = new BinaryReader(FileStream);
            IsFileOpen = true;
        }

        public byte ReadByte() => BinaryReader.ReadByte();
        public byte[] ReadBytes(int length) => BinaryReader.ReadBytes(length);

        public async Task<string> ReadToEndAsHexAsync()
        {
            var result = await Task.Run(() =>ReadToEndAsHex()).ConfigureAwait(false);
            return result;
        }

        public string ReadToEndAsHex()
        {
            StringBuilder sb = new StringBuilder();
            int count = 0;
            do
            {
                sb.Append(BitConverter.ToString(BinaryReader.ReadBytes(1)) + HexSpliter);
                if (count % 100 == 0)
                {
                    RaiseProgressChanged();
                    count = 0;
                }

                count++;
            } while (Progress < 100);
            RaiseProgressChanged();
            return sb.ToString();
        }

        private void RaiseProgressChanged() => RaisePropertyChanged(nameof(Progress));
    }
}
